//
//  EventDetailTableViewController.m
//  StanfordEvents
//
//  Created by Gongmyung on 7/20/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "EventDetailTableViewController.h"
#import "StanfordEventsAppDelegate.h";


@implementation EventDetailTableViewController

@synthesize setHidden;
@synthesize delegate;

#pragma mark -
#pragma mark View lifecycle

- (id)initWithStyle:(UITableViewStyle)style withEvent:(Event*)e {
    thisEvent = e;
    [thisEvent retain];
    setHidden = NO;
    return [super initWithStyle:style];
}

- (id)initWithStyle:(UITableViewStyle)style withEvent:(Event*)e setHidden:(bool)hidden {
    thisEvent = e;
    [thisEvent retain];
    setHidden = hidden;
    return [super initWithStyle:style];             
}

- (void)viewDidLoad {
    
    self.title = thisEvent.title;
    
    addButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"117-todo.png"] style:UIBarButtonItemStylePlain target:self action:@selector(checkIn)];
    StanfordEventsAppDelegate *appDelegate = (StanfordEventsAppDelegate*)[[UIApplication sharedApplication] delegate];
    
    //check to see if we are within 1 mile of the event
    double x = (appDelegate.eventsListViewController.locationManager.location.coordinate.latitude-[thisEvent.latitude doubleValue])*69.1;
    double y = (appDelegate.eventsListViewController.locationManager.location.coordinate.longitude-[thisEvent.longitude doubleValue])*69.1;
    double dist = sqrt( x*x+y*y );
    
    NSLog(@"distance: %d, attended:%i", dist, [thisEvent.attended intValue]);
    
    if( dist < 0.8 && [thisEvent.attended intValue] != 1 ) {
        addButton.enabled = YES;
    }
    else {
        addButton.enabled = NO;
    }
    self.navigationItem.rightBarButtonItem = addButton;
    
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    //self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    switch (indexPath.section) {
        case 0:
            return 88;
            break;
        case 1:
            return 66;
            break;
        default:
            return 44;
            break;
    }
    return 80.0; //returns floating point which will be used for a cell row height at specified row index  
}  

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    static NSString *DescriptionCellIdentifier = @"descriptionCell";
    static NSString *DateCellIdentifier = @"dateCell";
    UITableViewCell *cell;
    EventDescriptionTableCell *descCell;
    EventDateTableCell *dateCell;
    
    // Configure the cell...
    switch (indexPath.section) {
        case 0:
            descCell = (EventDescriptionTableCell*)[tableView dequeueReusableCellWithIdentifier:DescriptionCellIdentifier];
            if (descCell == nil) {
                NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"EventDescriptionTableCell" owner:nil options:nil];
                
                for(id currentObject in nibObjects ) {
                    if([currentObject isKindOfClass:[EventDescriptionTableCell class]]) {
                        descCell = (EventDescriptionTableCell*)currentObject;
                        break;
                    }
                }
            }
            
            descCell.eventTitle.text = [thisEvent title];
            descCell.eventDescription.text = [thisEvent eventdescription];
            descCell.eventHost.text = [NSString stringWithFormat:@"Hosted by: %@",[thisEvent host]];
            descCell.accessoryType = UITableViewCellAccessoryNone;
            cell = descCell;
            break;
        case 1:
            dateCell = (EventDateTableCell*)[tableView dequeueReusableCellWithIdentifier:DateCellIdentifier];
            if (dateCell == nil) {
                NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"EventDateTableCell" owner:nil options:nil];
                
                for(id currentObject in nibObjects ) {
                    if([currentObject isKindOfClass:[EventDateTableCell class]])
                        dateCell = (EventDateTableCell*)currentObject;
                }
            }
            if( thisEvent.starttime == nil || thisEvent.endtime == nil ) {
                dateCell.startDate.text = @"";
                dateCell.endDate.text = @"";
            }
            else {
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
                [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
                dateCell.startDate.text = [dateFormatter stringFromDate:[thisEvent starttime]];
                dateCell.endDate.text = [dateFormatter stringFromDate:[thisEvent endtime]];
            }
            dateCell.accessoryType = UITableViewCellAccessoryNone;
            cell = dateCell;
            break;
        case 2:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            }
            [cell.textLabel setText:[thisEvent location]];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
        case 3:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            }
            [cell.textLabel setText:@"View Attendees"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
        default:
            break;
    }
    return cell;
}


- (IBAction) checkIn {
    StanfordEventsAppDelegate *appDelegate = (StanfordEventsAppDelegate*)[[UIApplication sharedApplication] delegate];
    NSString *username, *password;
    NSUserDefaults *defaultSettings = [NSUserDefaults standardUserDefaults];
    username = [defaultSettings stringForKey:@"username"];
    password = [defaultSettings stringForKey:@"password"];
    
    NSMutableDictionary *requestDict = [[NSMutableDictionary alloc] init];
    [requestDict setObject:[NSNumber numberWithDouble:appDelegate.eventsListViewController.locationManager.location.coordinate.latitude] forKey:@"latitude"];
    [requestDict setObject:[NSNumber numberWithDouble:appDelegate.eventsListViewController.locationManager.location.coordinate.longitude] forKey:@"longitude"];
    //one degree of latitude = 69 miles, do a simple conversion here (divide by 2 for radius):
    [requestDict setObject:[thisEvent.eid stringValue] forKey:@"eid"];
    [requestDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"time"];
    NSLog(@"about to parse json object");
    
    //parse object into json
    SBJSON *sparser = [[SBJSON alloc] init];
    NSString *jsonEvent = [sparser stringWithObject:requestDict];
    
    //create a get request
    NSURL *url = [NSURL URLWithString:@"http://colby.stanford.edu/community_vibe/concierge/rpc.php"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    [request setPostValue:username forKey:@"name"];
    [request setPostValue:password forKey:@"key"];
    [request setPostValue:@"postMessage" forKey:@"do"];
    [request setPostValue:jsonEvent forKey:@"content"];    
    [request setPostValue:@"stanford_events,checkin" forKey:@"tags"];
    [request startSynchronous];
    
    NSString *response;
    NSError *error = [request error];
    if (!error) {
        response = [request responseString];
        //NSLog(response);
    }
    
    [thisEvent setAttended:[NSNumber numberWithInt:1]];
    
    UIAlertView *success = [[UIAlertView alloc]
                            initWithTitle:@"Check-in Success!"
                            message:[NSString stringWithFormat: @"You have been checked in to event %@", [thisEvent title]]
                            delegate:self
                            cancelButtonTitle:@"Ok"
                            otherButtonTitles: nil];
    [success show];
    [success autorelease];
    addButton.enabled = NO;
    
    error;
    if (![appDelegate.eventsListViewController.managedObjectContext save:&error]) {
        NSLog(@"failed to save created event");
    }
    
    if( self.delegate != nil ) {
        [self.delegate didCheckIn];
    }
    
    //need this to refresh "my events" whenever we check in to an event
    [appDelegate.eventsListViewController addEventToList:thisEvent];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if( indexPath.section == 0 ) {
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:thisEvent.title message:thisEvent.eventdescription delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil];
        [myAlertView show];
        [myAlertView release];

    }
    else if( indexPath.section == 1 ) {
    }
    else if( indexPath.section == 2 ) {
        StanfordEventsAppDelegate *appDelegate = (StanfordEventsAppDelegate*)[[UIApplication sharedApplication] delegate];
        MapViewController *mapViewController = appDelegate.mapViewController;
        [mapViewController centerAtLatitude:[thisEvent.latitude doubleValue] longitude:[thisEvent.longitude doubleValue] withSelected:[thisEvent.eid intValue]];
        appDelegate.tabController.selectedViewController = appDelegate.mapController;
    }
    else {
        NSString *username, *password;
        NSUserDefaults *defaultSettings = [NSUserDefaults standardUserDefaults];
        username = [defaultSettings stringForKey:@"username"];
        password = [defaultSettings stringForKey:@"password"];
        
        //parse object into json
        SBJSON *parser = [[SBJSON alloc] init];
        
        //create a get request
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://colby.stanford.edu/community_vibe/orientation/eventRosterJSON.php?eid=%@", thisEvent.eid]];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request startSynchronous];
        
        NSString *response;
        NSError *error = [request error];
        if (!error) {
            response = [request responseString];
            //parse json
            NSArray *responseArray = [parser objectWithString:response];
            NSMutableArray *attendeeArray = [[NSMutableArray alloc] init];
            for (NSString *attendeeData in responseArray ) {
                NSDictionary *data = [parser objectWithString:attendeeData];
                Attendee *a = [[Attendee alloc] initWithName:[data objectForKey:@"name"] userID:[data objectForKey:@"pid"]];
               // NSLog(a.name);
               // NSLog(a.pid);
                [attendeeArray addObject:a];
                [a release];
            }
            AttendeeListViewController *attendeesViewController = [[AttendeeListViewController alloc] initWithStyle:UITableViewStylePlain withAttendees:attendeeArray setHidden:setHidden];
            [self.navigationController pushViewController:attendeesViewController animated:YES];
            [attendeesViewController release];
            [attendeeArray release];
        }
    }
}


#pragma mark -
#pragma mark Memory management

//for hiding the navigation bar when we go back to the map view
- (void)viewWillDisappear:(BOOL)animated {
	if( setHidden ) {
		[self.navigationController setNavigationBarHidden:YES animated:YES];
	}
	[super viewWillDisappear:animated];
}

//for hiding the navigation bar when we go back to the map view
- (void)viewWillAppear:(BOOL)animated {
	if( setHidden ) {
		[self.navigationController setNavigationBarHidden:NO animated:NO];
	}
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [thisEvent release];
    [super dealloc];
}


@end

